package package1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestForJingju {

	public static String musicAddr = "";
	public static String xmlAddr = "";
	public static void main(String[] args) throws Exception {
		init();
		readName();
		changeName();
	}
	private static void readName() throws IOException, Exception {
		List<String> list = new ArrayList<String>();
		for(File f:new File(musicAddr).listFiles()){
			list.add(f.getName());
		}
		System.err.println("list:"+list);
		List<String> list2 = list.subList(0,10);
		
		File f = new File("C:\\Users\\Administrator\\Desktop\\生日表.xlsx");
		File f2 = new File("C:\\Users\\Administrator\\Desktop\\test.xlsx");
		InputStream is = new FileInputStream(f);
		Workbook wb = new XSSFWorkbook(is);
		XSSFSheet sheet = (XSSFSheet) wb.getSheetAt(0);
		XSSFRow row = sheet.getRow(0);
		int column = row.getLastCellNum();
		XSSFCell cell = row.createCell(column);
		cell.setCellValue(new SimpleDateFormat("yyyy.MM.dd").format(new Date()));
		for(int i=0;i<list2.size();i++){
			sheet.getRow(i).createCell(column).setCellValue(list2.get(i));
		}
		OutputStream os = null;
		try {
			os = new FileOutputStream(f2);
		} catch (Exception e) {
			if(e.getMessage().contains("另一个程序正在使用此文件，进程无法访问")){
				System.err.println("出现错误，准备关闭excel");
				run("taskkill /f /im excel.exe");
				System.err.println("excel shut down");
				Thread.sleep(100);
				os = new FileOutputStream(f2);
				System.err.println("os = new ...");
			}
		}
		wb.write(os);
		os.close();
		System.err.println("success");
		open(f2);
//		System.err.println(cell.equals(null));
//		System.err.println(cell.getRawValue()==null);
	}
	private static void run(String string) throws IOException {
		Process p = Runtime.getRuntime().exec(string);
	}
	
	private static void changeName() {
		
	}
	private static void init() throws IOException {
		musicAddr = "E:\\下载\\京剧\\[57magic.com]京剧MP3全剧112首下载";
		xmlAddr = "E:\\下载\\京剧\\jingju.xlsx";
//		open(musicAddr);
	}
	private static void open(String f) throws IOException {
		open(new File(f));
	}
	private static void open(File f) throws IOException {
		java.awt.Desktop.getDesktop().open(f);
	}
	private static String getDesktop() {
		return System.getenv("USERPROFILE") + "\\desktop\\";
	}

}
